package yagwl.client.view.demo;

import java.util.List;

import yagwl.client.model.ItemDTO;
import yagwl.client.model.demo.LaureateListCache;
import yagwl.client.widget.PagedFlexTable;
import yagwl.client.widget.PagedFlexTable.Action;
import yagwl.client.widget.PagedFlexTable.RowActionCallback;
import yagwl.client.widget.Section;
import yagwl.client.widget.Spacer;
import yagwl.shared.demo.LaureateConstants;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;

public class LaureateListView extends Composite {

  private final Section rootSP = new Section("Nobel Laureates");
  private final LaureateListCache listCache = new LaureateListCache();
  private final PagedFlexTable rootDT = new PagedFlexTable(listCache);

  public final static String HistoryToken = "laureateList";

  public LaureateListView() {
    listCache.setHistoryToken(HistoryToken);
    draw();
    initWidget(rootSP);
  }

  private void draw() {
    rootSP.setDescription(new HTML(desc));
    rootSP.setFootnote("Data from wikipedia; parsing errors possible.");
    rootDT.addColumn(Column.Year.ordinal(), "Year");
    rootDT.addColumn(Column.Category.ordinal(), "Category");
    rootDT.addColumn(Column.Photo.ordinal(), "Photo");
    rootDT.addColumn(Column.Name.ordinal(), "Name", "100px");
    rootDT.addColumn(Column.Country.ordinal(), "Country", "100px");
    rootDT.addColumn(Column.Rationale.ordinal(), "Rationale");
    rootDT.addSortOrderOption(LaureateConstants.SortYearAsc, "Earliest First");
    rootDT.addSortOrderOption(LaureateConstants.SortYearDesc, "Latest First");
    rootDT.addSortOrderOption(LaureateConstants.SortCountryAsc,
        "Country Ascending");
    rootDT.addSortOrderOption(LaureateConstants.SortCountryDesc,
        "Country Descending");
    rootDT.addSortOrderOption(LaureateConstants.SortCatAscYearAsc,
        "Category Asc, Earliest First");
    rootDT.addSortOrderOption(LaureateConstants.SortCatAscYearDesc,
        "Category Asc, Latest First");
    rootDT.addSortOrderOption(LaureateConstants.SortCatDescYearAsc,
        "Category Desc, Earliest First");
    rootDT.addSortOrderOption(LaureateConstants.SortCatDescYearDesc,
        "Category Desc, Latest First");
    rootDT.setSortOrderOptionIndex(1);
    int[] pageSizeOptions = { 10, 20, 50, 100 };
    rootDT.setPageSizeOptions(pageSizeOptions);
    rootDT.setPageSizeOptionIndex(1);
    rootDT.enableRowEdit();
    rootDT.addCustomRowAction("img/rss12o.gif",
        "Show Row Id (Custom Row Action)");
    rootDT.enableRowDelete();
    rootDT.setRowActionCallback(new LaureateRowActionCallback());
    rootDT.enableMultiSelect();
    rootDT.addButton("Show Selected", new ShowSelectionHandler());

    rootDT.renderUI();

    rootSP.setContent(rootDT);
  }

  private class LaureateRowActionCallback implements RowActionCallback {

    @Override
    public void action(Action action, int dataRowIdx, int objIdx) {
      ItemDTO lo = (ItemDTO) listCache.getList().get(objIdx);
      switch (action) {
      case Populate:
        rootDT.setCellText(dataRowIdx, Column.Year.ordinal(), lo.get("year"));
        rootDT.setCellText(dataRowIdx, Column.Category.ordinal(), lo
            .get("category"));
        if (lo.get("photo") != null && !lo.get("photo").equals(""))
          rootDT.setCellWidget(dataRowIdx, Column.Photo.ordinal(), new Image(lo
              .get("photo")));
        else { // clear out previous photo
          // there seems to be a bug, clearCell isnt working always
          // rootTP.clearCell(tableRow, Photo);
          rootDT.setCellWidget(dataRowIdx, Column.Photo.ordinal(), new Spacer(
              1, 1));
        }
        // rootDT.setCellWidget(dataRowIdx, Column.Name.ordinal(), new HTML(
        //     "<a href=" + "http://en.wikipedia.org" + lo.get("nameLink")
        //         + " target=_blank>" + lo.get("name") + "</a>"));
        rootDT.setCellWidget(dataRowIdx, Column.Name.ordinal(), new Anchor(lo
            .get("name"), "http://en.wikipedia.org" + lo.get("nameLink"),
            "_blank>"));
        rootDT.setCellText(dataRowIdx, Column.Country.ordinal(), lo
            .get("country"));
        rootDT.setCellText(dataRowIdx, Column.Rationale.ordinal(), lo
            .get("rationale"));
        break;
      case PreEdit:
        TextBox countryTB = new TextBox();
        countryTB.setValue((String) lo.get("country"));
        countryTB.setWidth("96px");
        rootDT.setCellWidget(dataRowIdx, Column.Country.ordinal(), countryTB);
        TextArea ratTA = new TextArea();
        ratTA.setValue((String) lo.get("rationale"));
        ratTA.setWidth("280px");
        rootDT.setCellWidget(dataRowIdx, Column.Rationale.ordinal(), ratTA);
        break;
      case PostEdit:
        TextBox countryTB1 = (TextBox) rootDT.getCellWidget(dataRowIdx,
            Column.Country.ordinal());
        lo.put("country", countryTB1.getValue());
        TextArea ratTA1 = (TextArea) rootDT.getCellWidget(dataRowIdx,
            Column.Rationale.ordinal());
        lo.put("rationale", ratTA1.getValue());
        listCache.updateObject(lo);
        break;
      case Custom:
        rootDT.setMessage("Custom action clicked for object " + objIdx);
        break;
      }
    }
  }

  private class ShowSelectionHandler implements ClickHandler {
    @Override
    public void onClick(ClickEvent event) {
      List list = listCache.getList();
      StringBuffer sbuf = new StringBuffer();
      for (int i = 0; i < list.size(); i++) {
        ItemDTO dobj = (ItemDTO) list.get(i);
        if (dobj.isSelected()) {
          sbuf.append(i + " ");
        }
      }
      if (sbuf.length() > 0)
        rootDT.setMessage(sbuf.append("selected").toString());
      else
        rootDT.setErrorMessage("None selected");
    }
  }

  private enum Column {
    Year, Category, Photo, Name, Country, Rationale
  }

  private static final String desc = "PagedFlexTable builds on GWT FlexTable, and implements common patterns in tables:"
      + "<ul>"
      + "<li>Data Fetch: programmable data fetch size (100 in this demo); fetched data cached in the browser memory; DataTable widget listens to custom event, ItemListEvent, to populate rows; rows populated via callback to the calling program"
      + "<li>Data display: variable and programmable display range; sort options; sort performed via callback, server side or client side"
      + "<li>Pagination: range indicator (x-y); indicates total if known (x-y of n); scrolls to top if at bottom; browser back button support"
      + "<li>Row Action: Multi-row selection; create, delete, edit row; row detail (not in this demo); custom row level actions (handled via callback)"
      + "<li>Not planned: Column grouping, column re-arrange/hide-show/freeze, column sorting and filtering (QBE).";

}
